var mongoose = require('mongoose');
const User = require('../model/user.model');
//增
exports.create = function(req, res, next) {
        const user = new User(req.body);
        //实例化对象，req.body代表的事post的数据提交，并且参数从body中获取        
        user.save().then(data => {
            //数据保存，在保存以后将数据用json形式进行输出
            res.json(data);
        })
    }
    //删
exports.remove = function(req, res, next) {
        const id = req.params.id;
        User.findByIdAndRemove(id, function(err, data) {
            res.json({ message: '删除成功' })
        })
    }
    //改 req.body,req.query,req.params(斜杠....)
exports.update = function(req, res, next) {
        const id = req.params.id;
        User.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
            res.json(data);
        })
    }
    //查
exports.list = function(req, res, next) {
    const page = req.body.page ? req.body.page : 1;
    var limit = req.body.limit ? req.body.limit : 5;
    var queryconditions = {};
    if (req.body.name && req.body.name.trim().length > 0) {
        name = req.body.name;
        queryconditions = {
            name: new RegExp(name, 'i')
        };
    };

    if (req.body.cateId && req.body.cateId.trim().length > 0) {
        cateId = req.body.cateId;
        //对象合并
        queryconditions = Object.assign(queryconditions, {
            cateId: cateId
        });
    };

    User.paginate(queryconditions, { page: page, limit: limit }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    })
}